package com.tzkyzj.tiremanagersystem.ui;

import static android.content.ContentValues.TAG;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.textfield.TextInputEditText;
import com.tzkyzj.tiremanagersystem.R;
import com.tzkyzj.tiremanagersystem.eneities.Tire;
import com.tzkyzj.tiremanagersystem.api.TireApiService;
import com.tzkyzj.tiremanagersystem.network.ApiClient;
import com.tzkyzj.tiremanagersystem.network.ApiResponse;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class AddRepairActivity extends AppCompatActivity {

    private static final int PICK_IMAGES_REQUEST = 1001;

    private Tire tire;
    private List<Uri> selectedPhotos = new ArrayList<>();

    private TextView tvTireNumber;
    private TextInputEditText etRepairRecord, etRepairMileage, etRepairCost;
    private MaterialButton btnSelectPhotos, btnSubmit, btnCancel;
    private RecyclerView rvPhotoPreview;
    private ProgressBar progressBar;
    private TextView tvProgress;

    private PhotoPreviewAdapter photoPreviewAdapter;
    private TireApiService apiService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_repair);

        // 获取传递的轮胎数据
        tire = (Tire) getIntent().getSerializableExtra("tire");
        if (tire == null) {
            finish();
            return;
        }

        // 初始化API服务
        apiService = ApiClient.getClient().create(TireApiService.class);

        initViews();
        setupRecyclerView();
        setupClickListeners();
        bindData();
    }

    private void initViews() {
        tvTireNumber = findViewById(R.id.tvTireNumber);
        etRepairRecord = findViewById(R.id.etRepairRecord);
        etRepairMileage = findViewById(R.id.etRepairMileage);
        etRepairCost = findViewById(R.id.etRepairCost);
        btnSelectPhotos = findViewById(R.id.btnSelectPhotos);
        btnSubmit = findViewById(R.id.btnSubmit);
        btnCancel = findViewById(R.id.btnCancel);
        rvPhotoPreview = findViewById(R.id.rvPhotoPreview);
        progressBar = findViewById(R.id.progressBar);
        tvProgress = findViewById(R.id.tvProgress);
    }

    private void setupRecyclerView() {
        photoPreviewAdapter = new PhotoPreviewAdapter(selectedPhotos);
        rvPhotoPreview.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        rvPhotoPreview.setAdapter(photoPreviewAdapter);
    }

    private void setupClickListeners() {
        btnSelectPhotos.setOnClickListener(v -> selectPhotos());
        btnSubmit.setOnClickListener(v -> submitRepairRecord());
        btnCancel.setOnClickListener(v -> finish());
    }

    private void bindData() {
        tvTireNumber.setText(tire.getTireNumber());
        if (tire.getInstallMileage() != null) {
            etRepairMileage.setText(String.valueOf(tire.getInstallMileage()));
        }
    }

    private void selectPhotos() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
        startActivityForResult(Intent.createChooser(intent, "选择照片"), PICK_IMAGES_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGES_REQUEST && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                if (data.getClipData() != null) {
                    // 多选照片
                    int count = data.getClipData().getItemCount();
                    for (int i = 0; i < count; i++) {
                        Uri imageUri = data.getClipData().getItemAt(i).getUri();
                        selectedPhotos.add(imageUri);
                    }
                } else if (data.getData() != null) {
                    // 单选照片
                    selectedPhotos.add(data.getData());
                }
                photoPreviewAdapter.notifyDataSetChanged();
            }
        }
    }

    private void submitRepairRecord() {
        String repairRecord = etRepairRecord.getText().toString().trim();
        String repairMileageStr = etRepairMileage.getText().toString().trim();
        String repairCostStr = etRepairCost.getText().toString().trim();

        // 验证输入
        if (repairRecord.isEmpty()) {
            etRepairRecord.setError("请输入修补描述");
            return;
        }

        if (repairMileageStr.isEmpty()) {
            etRepairMileage.setError("请输入修补公里数");
            return;
        }

        if (repairCostStr.isEmpty()) {
            etRepairCost.setError("请输入修补费用");
            return;
        }

        try {
            int repairMileage = Integer.parseInt(repairMileageStr);
            double repairCost = Double.parseDouble(repairCostStr);

            // 显示进度
            showProgress(true);

            // 使用Android专用接口 - 创建RequestBody而不是MultipartBody.Part
            RequestBody repairRecordBody = RequestBody.create(MediaType.parse("text/plain"), repairRecord);
            RequestBody repairMileageBody = RequestBody.create(MediaType.parse("text/plain"), String.valueOf(repairMileage));
            RequestBody repairCostBody = RequestBody.create(MediaType.parse("text/plain"), String.valueOf(repairCost));

            List<MultipartBody.Part> photoParts = createPhotoParts();


            // 调用Android专用API
            Call<ApiResponse<Void>> call = apiService.addRepairRecord(
                    tire.getId(), repairRecordBody, repairMileageBody, repairCostBody, photoParts);

            call.enqueue(new Callback<ApiResponse<Void>>() {
                @Override
                public void onResponse(Call<ApiResponse<Void>> call, Response<ApiResponse<Void>> response) {
                    showProgress(false);

                    if (response.isSuccessful() && response.body() != null) {
                        if (response.body().isSuccess()) {
                            Toast.makeText(AddRepairActivity.this, "添加修补记录成功", Toast.LENGTH_SHORT).show();
                            setResult(Activity.RESULT_OK);
                            finish();
                        } else {
                            String errorMsg = response.body().getMessage();
                            Toast.makeText(AddRepairActivity.this, "添加失败: " + errorMsg, Toast.LENGTH_SHORT).show();
                            Log.e(TAG, "API返回失败: " + errorMsg);
                        }
                    } else {
                        String errorMsg = "请求失败";
                        if (response.errorBody() != null) {
                            try {
                                errorMsg = response.errorBody().string();
                            } catch (IOException e) {
                                Log.e(TAG, "读取错误响应失败", e);
                            }
                        }
                        Toast.makeText(AddRepairActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
                        Log.e(TAG, "响应不成功: " + response.code() + " - " + errorMsg);
                    }
                }

                @Override
                public void onFailure(Call<ApiResponse<Void>> call, Throwable t) {
                    showProgress(false);
                    String errorMsg = "网络请求失败: " + t.getMessage();
                    Toast.makeText(AddRepairActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
                    Log.e(TAG, errorMsg, t);
                }
            });

        } catch (NumberFormatException e) {
            showProgress(false);
            Toast.makeText(this, "请输入有效的数字", Toast.LENGTH_SHORT).show();
            Log.e(TAG, "数字格式错误", e);
        } catch (Exception e) {
            showProgress(false);
            Toast.makeText(this, "处理数据时发生错误", Toast.LENGTH_SHORT).show();
            Log.e(TAG, "处理数据异常", e);
        }
    }

    /**
     * 创建照片部分的MultipartBody.Part列表
     */
    private List<MultipartBody.Part> createPhotoParts() {
        List<MultipartBody.Part> photoParts = new ArrayList<>();

        if (!selectedPhotos.isEmpty()) {
            for (int i = 0; i < selectedPhotos.size(); i++) {
                Uri photoUri = selectedPhotos.get(i);
                try {
                    File photoFile = uriToFile(photoUri, "repair_photo_" + i + ".jpg");
                    if (photoFile != null && photoFile.exists()) {
                        // 获取正确的MIME类型
                        String mimeType = getMimeType(photoUri);
                        MediaType mediaType;

                        if (mimeType != null && !mimeType.isEmpty()) {
                            mediaType = MediaType.parse(mimeType);
                        } else {
                            // 根据文件扩展名推断
                            String ext = getFileExtension(photoFile).toLowerCase();
                            switch (ext) {
                                case ".png":
                                    mediaType = MediaType.parse("image/png");
                                    break;
                                case ".gif":
                                    mediaType = MediaType.parse("image/gif");
                                    break;
                                case ".webp":
                                    mediaType = MediaType.parse("image/webp");
                                    break;
                                default:
                                    mediaType = MediaType.parse("image/jpeg");
                            }
                        }

                        if (mediaType == null) {
                            mediaType = MediaType.parse("image/jpeg");
                        }

                        RequestBody photoRequestBody = RequestBody.create(mediaType, photoFile);
                        MultipartBody.Part photoPart = MultipartBody.Part.createFormData(
                                "repairPhotos",
                                photoFile.getName(),
                                photoRequestBody
                        );
                        photoParts.add(photoPart);
                        Log.d(TAG, "成功创建照片Part: " + photoFile.getName() + ", 类型: " + mediaType.toString());
                    }
                } catch (IOException e) {
                    Log.e(TAG, "处理照片文件时出错: " + e.getMessage());
                    // 继续处理其他照片，不中断整个流程
                }
            }
        }

        Log.d(TAG, "共创建 " + photoParts.size() + " 个照片Part");
        return photoParts;
    }

    // 添加获取MIME类型的方法
    private String getMimeType(Uri uri) {
        ContentResolver contentResolver = this.getContentResolver();
        return contentResolver.getType(uri);
    }

    // 添加获取文件扩展名的方法
    private String getFileExtension(File file) {
        String name = file.getName();
        int lastDot = name.lastIndexOf('.');
        return lastDot != -1 ? name.substring(lastDot) : ".jpg";
    }

    /**
     * 将Uri转换为File
     */
    private File uriToFile(Uri uri, String fileName) throws IOException {
        InputStream inputStream = getContentResolver().openInputStream(uri);
        if (inputStream == null) {
            throw new IOException("无法打开文件流: " + uri);
        }

        File tempDir = new File(getCacheDir(), "temp_photos");
        if (!tempDir.exists()) {
            if (!tempDir.mkdirs()) {
                throw new IOException("无法创建临时目录");
            }
        }

        File tempFile = new File(tempDir, fileName);

        FileOutputStream outputStream = new FileOutputStream(tempFile);
        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        outputStream.close();
        inputStream.close();

        return tempFile;
    }



    private void showProgress(boolean show) {
        progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
        tvProgress.setVisibility(show ? View.VISIBLE : View.GONE);
        btnSubmit.setEnabled(!show);
        btnSelectPhotos.setEnabled(!show);

        if (show) {
            tvProgress.setText("正在提交修补记录...");
        }
    }

    // 照片预览适配器
    // 照片预览适配器
    private class PhotoPreviewAdapter extends RecyclerView.Adapter<PhotoPreviewAdapter.PhotoViewHolder> {
        private List<Uri> photos;

        public PhotoPreviewAdapter(List<Uri> photos) {
            this.photos = photos;
        }

        @NonNull
        @Override
        public PhotoViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_photo_preview, parent, false);
            return new PhotoViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull PhotoViewHolder holder, int position) {
            holder.bind(photos.get(position), position);
        }

        @Override
        public int getItemCount() {
            return photos.size();
        }

        class PhotoViewHolder extends RecyclerView.ViewHolder {
            private ImageView ivPhoto;
            private ImageButton btnRemove;

            public PhotoViewHolder(@NonNull View itemView) {
                super(itemView);
                ivPhoto = itemView.findViewById(R.id.ivPhoto);
                btnRemove = itemView.findViewById(R.id.btnRemove);
            }

            public void bind(Uri photoUri, int position) {
                // 加载照片
                Glide.with(itemView.getContext())
                        .load(photoUri)
                        .placeholder(R.drawable.ic_photo_placeholder)
                        .error(R.drawable.ic_photo_error)
                        .into(ivPhoto);

                // 删除按钮点击事件
                btnRemove.setOnClickListener(v -> {
                    photos.remove(position);
                    notifyItemRemoved(position);
                    notifyItemRangeChanged(position, photos.size());
                    Log.d(TAG, "移除照片，剩余: " + photos.size());
                });
            }
        }
    }

    // 在 TireApiService 中添加接口方法
    // @Multipart
    // @POST("api/tires/{tireId}/repair")
    // Call<ApiResponse<Void>> addRepairRecord(
    //         @Path("tireId") Long tireId,
    //         @Part MultipartBody.Part repairRecord,
    //         @Part MultipartBody.Part repairMileage,
    //         @Part MultipartBody.Part repairCost,
    //         @Part List<MultipartBody.Part> repairPhotos
    // );
}